package com.julinggame.nettyim.handler;

import com.alibaba.fastjson2.JSONObject;
import com.julinggame.nettyim.*;
import com.julinggame.nettyim.comment.ChatMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;
import netscape.javascript.JSObject;

public class ChatHandler {
    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame)
    {

        //所有的消息读写都在在ChannelHandlerContext中
         //前端返回的websocket解析
        ChatMessage chatMessage = JSONObject.parseObject(frame.text(), ChatMessage.class);
        //只处理私聊消息
        switch (MessageType.match(chatMessage.getType())){
            case PRIVATE -> {
                if (StringUtil.isNullOrEmpty(chatMessage.getTarget())){
                    ctx.channel().writeAndFlush(Result.fail("请指定发送对象"));
                }else {
                    Channel channel = ImServer.USER_CHANNEL.get(chatMessage.getTarget());
                    if (channel == null|| !channel.isActive()){
                        ctx.channel().writeAndFlush(Result.fail("用户不在线"));
                        return;
                    }
                    //发送消息
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(chatMessage)));
                }
            }
            default -> ctx.channel().writeAndFlush(Result.fail("不支持的消息类型"));
        }
    }
}
